from Simulinux.Core.Blocks.Step import Step
from Simulinux.Views.Constants import MODE_NORMAL
from Simulinux.Views.View import SELECT_COLOR
from GenericBlockView import *

class SourcesStepView(GenericBlockView):
    block_class = Step
    def __init__(self, block, parent_view):
        GenericBlockView.__init__(self, block, parent_view)
        self.width = 40
        self.height = 40
        self._create_single_output_pin_view(0)
        self.__builder = self._parent_view.get_ui_builder()
        self.__props_dialog = self.__builder.get_object("dialogPropertiesStep")
        self.__entry_name = self.__builder.get_object("entryStepName")
        self.__entry_amplitude = self.__builder.get_object("entryStepAmplitude")
    def draw(self, context):
        self.set_color(context)
        x_b, y_b, w, h = context.text_extents(self.block.name)[:4]
        text_y = self.block.posy - TEXT_VPADDING
        text_x = self.block.posx + self.width/2 - w/2 + x_b
        context.move_to(text_x, text_y)
        context.show_text(self.block.name)
        context.rectangle(self.block.posx, self.block.posy, self.width, self.height)
        padx, pady = self.width/10, self.height/10
        x_bottom, y_bottom = self.block.posx + padx, self.block.posy + self.height - pady
        context.move_to(x_bottom, y_bottom)
        context.rel_line_to(self.width/2 - padx, 0)
        context.rel_line_to(0, - self.height + 2*pady)
        context.rel_line_to(self.width/2 - padx, 0)
        self._draw_pins(context)
        context.stroke()
    def edit_properties(self):
        #@todo: Add key press events: ESC (close dialog), ENTER (confirm changes)
        #@todo: Validate data before setting 
        self.__entry_name.set_text(self.block.name)
        self.__entry_amplitude.set_text(str(self.block.amplitude))
        self.__props_dialog.set_default_response(1)
        #self.__entry_name.grab_focus()
        response = self.__props_dialog.run()
        if response == 1: #Change properties
            self.block.name = self.__entry_name.get_text()
            self.block.amplitude = self.__entry_amplitude.get_text()
        self.__props_dialog.hide()
        self._parent_view.switch_mode(MODE_NORMAL)

if __name__=="__main__":
    step = Step()
    view = SourcesStepView(step)
    view.generate_pixmap("sources_step")
